package net.java.fixrouter;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import net.java.nioserver.BasicService;
import net.java.nioserver.aio.AioService;
import net.java.nioserver.sample.ConnectedOpAccept;
import net.java.nioserver.sample.EchoOpRead;
import net.java.nioserver.utils.NonBlockingByteBufferPool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Leonid Shlyapnikov
 */
public class FixRouterMain {

    private static final Logger log = LoggerFactory.getLogger(FixRouterMain.class);

    private static final long SHUTDOWN_TIMEOUT_MILLIS = 10000;

    public static void main(String argv[]) {
        final NonBlockingByteBufferPool byteBufferPool = new NonBlockingByteBufferPool(4, 20, true);
        
        AioService.Builder builder = new AioService.Builder();
        builder.address(new InetSocketAddress(1975))
                .executor(Executors.newFixedThreadPool(4))
                .byteBufferPool(byteBufferPool)
                .opRead(new EchoOpRead(byteBufferPool))
                .opAccept(new ConnectedOpAccept());

        final BasicService service = builder.build();

        // Register shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                log.info("Shutdown hook");
                service.stop(SHUTDOWN_TIMEOUT_MILLIS);
            }
        });

        int exitCode = 0;

        try {
            service.start();
        } catch (Exception e) {
            log.error("Cannot run FixRouter", e);
            exitCode = 100;
        } finally {
            service.stop(SHUTDOWN_TIMEOUT_MILLIS);
        }

        log.info("Exiting with exitCode: " + exitCode);
        System.exit(exitCode);
    }
}
